/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.activiti.explorer.demo;

import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.Picture;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.util.IoUtil;

/**
 * @author Joram Barrez
 */
public class DemoDataGenerator {

	protected static final Logger LOGGER = Logger
			.getLogger(DemoDataGenerator.class.getName());

	protected ProcessEngine processEngine;
	protected IdentityService identityService;

	public void setProcessEngine(ProcessEngine processEngine) {
		this.processEngine = processEngine;
		this.identityService = processEngine.getIdentityService();

		initDemoGroups();
		initDemoUsers();
	}

	protected void initDemoGroups() {
		String[] assignmentGroups = new String[] { "management", "sales",
				"marketing", "engineering", "bedelias", "instituto",
				"comisionInstituto", "comisionCarrera", "consejo" };
		for (String groupId : assignmentGroups) {
			createGroup(groupId, "assignment");
		}

		String[] securityGroups = new String[] { "user", "admin" };
		for (String groupId : securityGroups) {
			createGroup(groupId, "security-role");
		}
	}

	protected void createGroup(String groupId, String type) {
		if (identityService.createGroupQuery().groupId(groupId).count() == 0) {
			Group newGroup = identityService.newGroup(groupId);
			newGroup.setName(groupId.substring(0, 1).toUpperCase()
					+ groupId.substring(1));
			newGroup.setType(type);
			identityService.saveGroup(newGroup);
		}
	}

	protected void initDemoUsers() {
		createUser("kermit", "Kermit", "The Frog", "kermit",
				"kermit@activiti.org",
				"org/activiti/explorer/images/kermit.jpg", Arrays.asList(
						"management", "sales", "marketing", "engineering",
						"user", "admin", "bedelias", "instituto",
						"comisionInstituto", "comisionCarrera", "consejo"),
				Arrays.asList("birthDate", "10-10-1955", "jobTitle", "Muppet",
						"location", "Hollywoord", "phone", "+123456789",
						"twitterName", "alfresco", "skype",
						"activiti_kermit_frog"));

		createUser("gonzo", "Gonzo", "The Great", "gonzo",
				"gonzo@activiti.org", "org/activiti/explorer/images/gonzo.jpg",
				Arrays.asList("management", "sales", "marketing", "user",
						"bedelias"), null);
		createUser("fozzie", "Fozzie", "Bear", "fozzie", "fozzie@activiti.org",
				"org/activiti/explorer/images/fozzie.jpg",
				Arrays.asList("marketing", "engineering", "user", "bedelias"),
				null);
	}

	protected void createUser(String userId, String firstName, String lastName,
			String password, String email, String imageResource,
			List<String> groups, List<String> userInfo) {

		if (identityService.createUserQuery().userId(userId).count() == 0) {

			// Following data can already be set by demo setup script

			User user = identityService.newUser(userId);
			user.setFirstName(firstName);
			user.setLastName(lastName);
			user.setPassword(password);
			user.setEmail(email);
			identityService.saveUser(user);

			if (groups != null) {
				for (String group : groups) {
					identityService.createMembership(userId, group);
				}
			}
		}

		// Following data is not set by demo setup script

		// image
		if (imageResource != null) {
			byte[] pictureBytes = IoUtil.readInputStream(this.getClass()
					.getClassLoader().getResourceAsStream(imageResource), null);
			Picture picture = new Picture(pictureBytes, "image/jpeg");
			identityService.setUserPicture(userId, picture);
		}

		// user info
		if (userInfo != null) {
			for (int i = 0; i < userInfo.size(); i += 2) {
				identityService.setUserInfo(userId, userInfo.get(i),
						userInfo.get(i + 1));
			}
		}

	}

	protected void initProcessDefinitions() {
		processEngine
				.getRepositoryService()
				.createDeployment()
				.name("Demo processes")
				.addClasspathResource(
						"org/activiti/explorer/demo/process/testProcess.bpmn20.xml")
				.addClasspathResource(
						"org/activiti/explorer/demo/process/oneTaskProcess.bpmn20.xml")
				.addClasspathResource(
						"org/activiti/explorer/demo/process/createTimersProcess.bpmn20.xml")
				.deploy();
	}

}
